Skip to content

Bind descriptor accesses in find_member_simple (#22549) - #22553

Open
tony1233200 wants to merge 1 commit into
python:masterfrom
tony1233200:fix-descriptor-type-statement-22549
Open

tony1233200 wants to merge 1 commit into
python:masterfrom
tony1233200:fix-descriptor-type-statement-22549

Conversation

@tony1233200

Copy link
Copy Markdown

Fixes #22549.

A type statement like type A = Box[C] | int produced a false
positive Type argument "C" of "Box" must be a subtype of "P" when C
implements the protocol P via a descriptor attribute, and the wrong
result was then cached, so the later, valid check x: P = C() failed
as well.

Root cause: validating type variable bounds happens before type
checking (in semanal_typeargs), where member lookup falls back to
find_member_simple(). That helper returned the descriptor type itself
for a class attribute declared with a descriptor type (e.g. m: Desc),
instead of the type produced by binding __get__, so the protocol
check compared Desc against dict[str, int] and failed.

This makes find_member_simple() bind descriptor accesses for instance
attribute lookups: it resolves __get__ (selecting the overload that
applies to an instance access when overloaded), and falls back to the
previous behavior whenever the descriptor cannot be bound reliably
(no __get__, ambiguous overloads, lvalue or class-object accesses).

Tests: added regression tests in check-protocols.test and
check-python312.test (the latter is the exact repro from the issue),
plus a test that a genuinely incompatible descriptor still errors.

Test report:

  • New tests: 3 passed (and the two positive ones fail without the fix).
  • testcheck.py (protocols, python312, generics, generic-subtyping,
    generic-alias, type-aliases): 701 passed, 4 skipped.
  • testsubtypes.py: 26 passed.
  • Full testcheck.py suite: 8304 passed, 45 skipped, 7 xfailed.
  • black and ruff on mypy/subtypes.py: clean.

Note: this PR was prepared with LLM assistance.

Fixes python#22549

When checking type variable bounds before type checking (e.g. for
`type` statements), member lookup falls back to find_member_simple(),
which returned the descriptor type itself instead of binding __get__.
As a result, a class implementing a protocol via a descriptor failed
the bound check, and the wrong negative result was cached and reused
by later, accurate checks.
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

type statement false positive that gets cached and ruins otherwise accurate checks

1 participant